package com.baizhi.utils;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2019/6/24.
 */
public class LuceneUtil {
    /**
     * 静态属性
     */
    private static FSDirectory directory = null;

    public static StandardAnalyzer analyzer = null;

    /**
     * 静态代码块
     *
     */
    static {
        try {
            directory = FSDirectory.open(new File("E://Lucene"));
            analyzer = new StandardAnalyzer(Version.LUCENE_44);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取索引写出对象
     */
    public static IndexWriter getIndexWriter(){
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_44,analyzer);
        IndexWriter indexWriter = null;
        try {
            indexWriter = new IndexWriter(directory,indexWriterConfig);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexWriter;
    }

    /**
     * 关键词处理
     */
    public static Query queryParser(String keywords,String[] fields){
        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_44,fields,analyzer);
        Query query = null;
        try {
            query = queryParser.parse(keywords);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * 获取IndexSearcher对象
     */
    public static IndexSearcher getIndexSearcher(){
        DirectoryReader directoryReader = null;
        try {
            directoryReader = DirectoryReader.open(directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
        IndexSearcher indexSearcher = new IndexSearcher(directoryReader);
        return indexSearcher;
    }

}
